package com.test.sdk.scripts.service;

import com.test.sdk.scripts.util.QuartzManager;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.test.sdk.scripts.pojo.QuartzScripts;
import com.test.sdk.scripts.dao.QuartzScriptsDao;

@Service
public class QuartzScriptsService {
    @PostConstruct
    public void init() {
        List<QuartzScripts> scripts = quartzScriptsDao.getAllScripts(1);
        for (QuartzScripts script : scripts) {
            System.out.println(script);
            try {
                Class clazz = Class.forName(script.getJobClass());
                Map<String, Object> data = new HashMap<>();
                data.put("id", script.getId());
                //动态添加任务
                QuartzManager.addJob(script.getCron(), clazz, script.getJobClass(), data);
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        }
    }


    @Resource
    private QuartzScriptsDao quartzScriptsDao;

    public int insert(QuartzScripts pojo) {
        return quartzScriptsDao.insert(pojo);
    }

    public int update(QuartzScripts scripts) {
        return quartzScriptsDao.update(scripts);
    }

    public int update(String jobClass, String cron, Integer id) {
        QuartzManager.modifyJobTime(jobClass, cron);
        QuartzScripts scripts = new QuartzScripts();
        scripts.setId(id);
        scripts.setCron(cron);
        return quartzScriptsDao.update(scripts);
    }

    public List<QuartzScripts> getAllScripts(Integer status) {
        return quartzScriptsDao.getAllScripts(status);
    }

    //1运行中  0暂停
    public void pause(Integer id) {
        QuartzScripts scripts = quartzScriptsDao.getScriptById(id);
        if (scripts.getStatus() == 1) {
            QuartzManager.pauseJob(scripts.getJobClass());
            scripts.setStatus(0);//暂停
            quartzScriptsDao.update(scripts);
        }
    }

    public void resume(Integer id) {
        QuartzScripts scripts = quartzScriptsDao.getScriptById(id);
        if (scripts.getStatus() == 0) {
            //暂停状态是2
            if(QuartzManager.getJobStatus(scripts.getJobClass())==2) {
                QuartzManager.resumeJob(scripts.getJobClass());
            }else{
                try {
                    Class clazz = Class.forName(scripts.getJobClass());
                    Map<String, Object> data = new HashMap<>();
                    data.put("id", scripts.getId());
                    //动态添加任务
                    QuartzManager.addJob(scripts.getCron(), clazz, scripts.getJobClass(), data);
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
            }
            scripts.setStatus(1);//暂停
            quartzScriptsDao.update(scripts);
        }
    }
}
